const {
  getlistDetail,
  faChe,
  getOrder,
  jieDan,
  getCarList,
  carStatus,
  addRizhi
} = require('../../utils/api')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //权限控制 1-司机 2-站点
    quanxian: '',
    // 订单状态：1-待接单 2-进行中 3-已完成 4-接单
    orderStatus: 4,
    fileList: [],
    imageList: [],
    orderId: null,
    orderDetail: {},
    steps: [{
        text: '已发货',
        desc: '2023-07-20 14:00'
      },
      {
        text: '运输中',
        desc: '2023-07-21 09:00'
      },
      {
        text: '已签收',
        desc: '2023-07-22 16:30'
      }
    ],
    active: 2,
    order: {
      id: 1,
      status: 'pending',
      statusText: '待接单',
      goods: '电子设备（20kg）',
      price: 150,
      from: '上海浦东仓库',
      to: '徐汇区收货点',
      orderId: '88888888'
    },
    addressSteps: [{
        text: '发货地址',
        desc: '上海市浦东新区 张江高科技园区',
        customIcon: 'location-o',
        person: '李某某 138****1234',
        active: true // 控制激活状态
      },
      {
        text: '收货地址',
        desc: '北京市海淀区 中关村大街1号',
        customIcon: 'location',
        person: '王某某 139****5678',
        active: false
      }
    ]
  },
  getdetail(e) {
    const data = {
      filterByTk: e,
      appends: "f_driver,r_pd,f_a2u1smgkzwg"
    }
    getlistDetail(data).then(res => {
      this.setData({
        orderDetail: res.data
      })
    })
  },
  onCompleteService() {
    // 服务完成处理逻辑
  },

  onCancelOrder() {
    // 取消订单逻辑
    console.log('完成接单')
    wx.showModal({
      title: '确认完成',
      content: '您确定要完成接单吗？',
      confirmText: '确定完成',
      cancelText: '再想想',
      success: (res) => {
        if (res.confirm) {
          const uid = `filterByTk=${this.data.orderDetail.id}`
          this.setData({
            'orderDetail.f_status': 3, // 直接指定属性路径,
            'orderDetail.f_end': this.formatTime()
          })
          const data = this.data.orderDetail
          faChe(uid, data).then(res => {
            this.jiedanbiao(data)
            this.rizhi(data)
          }).catch(res => {

          })
        }
      }
    })
  },
  rizhi(e) {
    console.log('查看行车日志', e)
    const data = {
      f_car_id: e.f_a2u1smgkzwg.id,
      f_dispatch_id: e.r_pd.id,
      f_order: e.f_time,
      f_depart: e.f_start,
      f_arrive: e.f_end,
    }
    addRizhi(data).then(res => {

    }).catch(res => {

    })
  },
  // 拨打电话
  makePhoneCall(e) {
    const phone = e.currentTarget.dataset.phone
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },
  onAcceptOrder() {
    wx.showModal({
      title: '确认发车',
      content: '您确定要发车吗？',
      confirmText: '确定发车',
      cancelText: '再想想',
      success: (res) => {
        if (res.confirm) {
          this.handleRealAccept()
        }
      }
    })
  },

  handleRealAccept() {
    wx.showLoading({
      title: '接单中...'
    })
    const uid = `filterByTk=${this.data.orderDetail.id}`
    this.setData({
      'orderDetail.f_status': 4, // 直接指定属性路径,
      'orderDetail.f_start': this.formatTime()
    })
    const data = this.data.orderDetail
    faChe(uid, data).then(res => {
      this.jiedanbiao(data)
    }).catch(res => {

    })

  },
  jiedanbiao(data) {
    this.getOrderList() //查询派单列表
    this.carList() //查询车辆列表
  },
  //查询车辆列表
  carList() {
    const data = {
      page: '1',
      pageSize: '20',
      appends: "team,f_head,f_tail,f_driver",
      filter: {
        "$and": [{
          "f_head": {
            "f_number": {
              "$includes": this.data.orderDetail.f_a2u1smgkzwg.f_name
            }
          }
        }]
      }
    }
    getCarList(data).then(res => {
      this.chelaingStatus(res.data[0])
    })
  },
  //查询派单列表
  getOrderList() {
    const data = {
      page: '1',
      pageSize: '20',
      appends: "f_team",
      filter: {
        "$and": [{
          "f_num": {
            "$includes": this.data.orderDetail.r_pd.f_num
          }
        }]
      }
    }
    getOrder(data).then(res => {
      this.paidanStatus(res.data[0])
    })
  },
  //修改派单管理的派单状态
  paidanStatus(data) {
    const uid = `filterByTk=${data.id}`
    const dataJson = {
      f_status: data.f_status == 3 ? 4 : 5
    }
    jieDan(uid, dataJson).then(res => {
      wx.switchTab({
        url: '/pages/list/list' // 根据实际路径调整，需确保该路径已在 app.json 的 tabBar.list 中注册
      });
    }).catch(res => {

    })
  },
  chelaingStatus(data) {
    const uid = `filterByTk=${data.id}&triggerWorkflows=shcesziqyo6`
    const dataJson = {
      f_status: 1
    }
    carStatus(uid, dataJson).then(res => {
      wx.switchTab({
        url: '/pages/list/list' // 根据实际路径调整，需确保该路径已在 app.json 的 tabBar.list 中注册
      });
    }).catch(res => {

    })
  },

  formatTime(date = new Date()) {
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    return `${year}-${month}-${day}`
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      quanxian: wx.getStorageSync('quanxian')
    });
    this.getdetail(options.id)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})